qui(function (require, exports, module) {
    Specimen.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            specimen_operate: function (v, o, r) {
                var htmlArr = [];
                if (r.status == 1) {
                    htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.jumpToHostSpecimen(this)'>主持人帧采样</a>")
                    htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.jumpToNewsSpecimen(this)'>新闻标题采样</a>")
                } else {
                    htmlArr.push("<a class='disabled'>主持人帧采样</a>");
                    htmlArr.push("<a class='disabled'>新闻标题采样</a>");
                }

                htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.modifySpecimen(this)'>修改</a>")
                htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.delSpecimen(this)'>删除</a>")
                return htmlArr.join(" ").replace(/@id/g, r.qipu_id + "");
            },
            specimen_status: function (v, o, r) {
                return "已标注N个样本".replace("N", "" + v);
            },
            status: function (v, o, r) {
                var ret = "";
                v = parseInt(v);
                switch (v) {
                    case 0:
                        ret = "抽帧中";
                        break;
                    case 1:
                        ret = "已完成";
                        break;
                    case 2:
                        ret = "抽帧失败";
                        break;
                    default:
                        ret = "未知状态：" + v;
                        break;
                }
                return ret;
            },
            date_range: function (v, o, r) {
                return  r.start_time + "-" + r.end_time;
            },
            specimen_download: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.downloadHost(this)'>主持人帧</a>")
                htmlArr.push("<a href='javascript:;' data-id='@id' onclick='Specimen.Util.downloadNews(this)'>新闻标题</a>")
                return htmlArr.join(" ").replace(/@id/g, r.qipu_id + "");
            },
            download_url: function (v, o, r) {
                return "<a download='" + r.name + "' href='" + v + "'>样本下载</a>";
            }
        },
        downloadHost: function (element) {
            var elementData = Specimen.Config.PageBeanSpecimen.findData("qipu_id", $(element).attr("data-id"));
            var params = {
                qipu_id: elementData.qipu_id,
                album_id: elementData.album_id
            };
            Specimen.Dao.doDownShot(params, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({content: "下载（主持人帧）接口 异常", type: "error"})
                } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                    Specimen.Config.PageBeanDownload.setNewData(data.data.result);
                    Specimen.Util.openDownloadView(elementData.news_name, 0);
                } else {
                    EpgWeb.Plugin.showTips({content: data.msg, type: "error"})
                }
            })
        },

        downloadNews: function (element) {
            var elementData = Specimen.Config.PageBeanSpecimen.findData("qipu_id", $(element).attr("data-id"));
            var params = {
                qipu_id: elementData.qipu_id,
                album_id: elementData.album_id
            };
            Specimen.Dao.doDownTopic(params, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({content: "下载（新闻标题）接口 异常", type: "error"})
                } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                    Specimen.Config.PageBeanDownload.setNewData(data.data.result);
                    Specimen.Util.openDownloadView(elementData.news_name, 1);
                } else {
                    EpgWeb.Plugin.showTips({content: data.msg, type: "error"})
                }
            })
        },
        openDownloadView: function (news_name, table_mode) {
            $('#downloadDiv').dialog("option", "title", "新闻名称：" + news_name);
            $('#downloadDiv').dialog("open");
            var table_title = Specimen.Config.TABLE_TITLE[table_mode];
            $("#downloadList").setCaption(table_title);
            $("#downloadList")[0].addJSONData(Specimen.Config.PageBeanDownload.getCur());
        },
        jumpToHostSpecimen: function (element) {
            Specimen.Dao.doAuthData({
                url: '/epg/auth/specimen_senior',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: Specimen.Config.HINT_MSG.AUTH_FORBIDDEN, type: "error"})
                },
                doSuccess: function () {
                    var elementData = Specimen.Config.PageBeanSpecimen.findData("qipu_id", $(element).attr("data-id"));
                    var params = {
                        qipu_id: elementData.qipu_id,
                        album_id: elementData.album_id,
                        news_name: encodeURIComponent(elementData.news_name),
                        album_name: encodeURIComponent(elementData.album_name),
                        channel: encodeURIComponent(elementData.channel)
                    };
                    var openUrl = "specimen_host_frame.html?" + Specimen.Util.transGetParams(params)
                    window.open(openUrl);
                }
            })
        },
        jumpToNewsSpecimen: function (element) {

            Specimen.Dao.doAuthData({
                url: '/epg/auth/specimen_senior',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: Specimen.Config.HINT_MSG.AUTH_FORBIDDEN, type: "error"})
                },
                doSuccess: function () {
                    var elementData = Specimen.Config.PageBeanSpecimen.findData("qipu_id", $(element).attr("data-id"));
                    var params = {
                        qipu_id: elementData.qipu_id,
                        album_id: elementData.album_id,
                        news_name: encodeURIComponent(elementData.news_name),
                        album_name: encodeURIComponent(elementData.album_name),
                        channel: encodeURIComponent(elementData.channel)
                    };
                    var openUrl = "specimen_news_title.html?" + Specimen.Util.transGetParams(params)
                    window.open(openUrl);
                }
            })
        },
        addSpecimen: function () {
            Specimen.Dao.doAuthData({
                url: '/epg/auth/specimen_senior',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: Specimen.Config.HINT_MSG.AUTH_FORBIDDEN, type: "error"})
                },
                doSuccess: function () {
                    var openUrl = "specimen_edit.html";
                    window.open(openUrl);
                }
            })
        },
        modifySpecimen: function (element) {
            Specimen.Dao.doAuthData({
                url: '/epg/auth/specimen_senior',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: Specimen.Config.HINT_MSG.AUTH_FORBIDDEN, type: "error"})
                },
                doSuccess: function () {
                    var elementData = Specimen.Config.PageBeanSpecimen.findData("qipu_id", $(element).attr("data-id"));
                    var params = {
                        qipu_id: elementData.qipu_id,
                        album_id: elementData.album_id,
                        news_name: encodeURIComponent(elementData.news_name),
                        album_name: encodeURIComponent(elementData.album_name),
                        channel: encodeURIComponent(elementData.channel),
                        start_time: elementData.start_time,
                        end_time: elementData.end_time
                    };

                    var openUrl = "specimen_edit.html?" + Specimen.Util.transGetParams(params);
                    window.open(openUrl, "_blank");
                }
            })
        },
        goBackToList: function (keyMsg) {
            SystemDialog.queryConfirm("确认要" + keyMsg + "么？", function (flag) {
                if (flag) {
                    var openUrl = "specimen_list.html";
                    window.open(openUrl);
                }
            });
        },
        delSpecimen: function (element) {
            Specimen.Dao.doAuthData({
                url: '/epg/auth/specimen_senior',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: Specimen.Config.HINT_MSG.ATUH_FORBIDDEN_DEL, type: "error"})
                },
                doSuccess: function () {
                    var id = $(element).attr("data-id")
                    var data = Specimen.Config.PageBeanSpecimen.findData("qipu_id", id)
                    var $data = {qipu_id: data.qipu_id, album_id: data.album_id};
                    SystemDialog.queryConfirm("确认要删除么？", function (flag) {
                        if (flag) {
                            Specimen.Dao.delSpecimen($data, function (data) {
                                if (data == null) {
                                    EpgWeb.Plugin.showTips({type: "error", content: "Specimen delSpecimen has error" })
                                } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                                    EpgWeb.Plugin.showTips({content: "删除成功" });
                                    $("#list").trigger("reloadGrid");
                                } else {
                                    EpgWeb.Plugin.showTips({type: "error", content: data.msg })
                                }
                            })
                        }
                    })
                }
            })
        },
        fillAlbumData: function (element) {
            console.log("fillAlbumData" + element.value);
            var albumId = $(element).val();
            if (albumId.length == 0) {
                return;
            }
            if (!EpgWeb.Plugin.Validate.baseCheck({value: albumId, error: "专辑id格式错误", type: "positive"})) {
                return;
            }
            var parentDiv = $(element).parent().parent();
            Specimen.Util.cleanSpecimenCell(parentDiv);
            var options = {
                url: EpgWeb.Constant.thirdUrl_apis_search_area_url,
                data: {t: 1, filter_EQL_entityId: albumId},
                type: "get",
                success: function (data) {
                    console.log(" 加载专辑数据[" + albumId + "]结束");
                    if (data == null) {
                        EpgWeb.Plugin.showTips({type: "加载专辑数据[" + albumId + "] 接口异常", content: data.msg});
                    } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                        if (data.data.result.length > 0) {
                            var queryData = data.data.result[0];
                            Specimen.Util.fillSpecimenCell(parentDiv, queryData);
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: "不存在专辑id:" + albumId});
                        }
                    } else {
                        EpgWeb.Plugin.showTips({type: "error", content: data.msg});
                    }
                },
                error: function (data) {
                    console.log(" 加载专辑数据[" + albumId + "]失败");
                }
            }
            Specimen.Dao.sendProxy(options);
        },
        cleanSpecimenCell: function ($parent) {
            $parent.find("span[name=span_qipu_id]").html("");
            $parent.find("span[name=span_album_name]").html("");
            $parent.find("span[name=span_channel_name]").html("");
            $parent.attr("has-submit", false);
            $parent.find("span[name=hint_info]").parent().hide();
        },
        fillSpecimenCell: function ($parent, queryData) {
            $parent.attr("submit-dataid", queryData.qipuId);
            $parent.find("span[name=span_qipu_id]").html(queryData.qipuId);
            $parent.find("span[name=span_album_name]").html(queryData.displayName);
            $parent.find("span[name=span_channel_name]").html(queryData.channelName);
        },
        doErrorSpecimenCell: function (qipuId, msg, index) {
            var parent = $("div[submit-dataid=" + qipuId + "]")
            var infoSpanArr = parent.find("span[name=hint_info]");
            if (index == null) {
                index = 0;
            }
            var infoSpan = $(infoSpanArr[index]);
            infoSpan.removeClass("hint-info-red").removeClass("hint-info-green");
            infoSpan.addClass("hint-info-red");
            infoSpan.html(msg);
            infoSpan.parent().show();
        },
        doSucSpecimenCell: function (qipuId, msg) {
            var parent = $("div[submit-dataid=" + qipuId + "]");
            var infoSpan = parent.find("span[name=hint_info]");
            infoSpan.removeClass("hint-info-red").removeClass("hint-info-green");
            parent.attr("has-submit", true);
            infoSpan.addClass("hint-info-green");
            infoSpan.html(msg);
            infoSpan.parent().show();
        },
        //pic_addr_0
        fillImageZone: function (dataArr) {
            var htmlArr = [];
            var j = 0;
            $.each(dataArr, function (i, element) {
                j++;
                element.imgId = j;
                element.pid = j;
                element.src = Specimen.Util.makeUpHostImgUrl(element);
                htmlArr.push(Specimen.Util.replaceHostTpl(element));
            })
            Specimen.Config.PageBeanSpecimen.setNewData(dataArr);
            return htmlArr.join("");
        },
        makeUpHostImgUrl: function (element) {
            return element.pic_path + "/" + element.pic_addr + ".jpg"
        },

        replaceHostTpl: function (element) {
            return Specimen.Config.HOST_TEMPLATE.replace(/@src/, element.src).replace(/@pid/g, element.pid)
        },

        imgloadComplete: function (element) {
            console.log(element.width, element.height);
        },
        submitNewSpecimen: function () {
            var dataArr = $(".my-border");
            var newArr = [];
            var validArr = [];
            $.each(dataArr, function (i, element) {
                var targetDiv = $(element);
                var submitData = {album_id: null, qipu_id: null, news_name: null, album_name: null, channel: null, start_time: null, end_time: null};
                if ("true" != targetDiv.attr("has-submit")) {
                    submitData.album_id = targetDiv.find("input[name=input_album_id]").val();
                    submitData.news_name = targetDiv.find("input[name=input_news_name]").val().trim();
                    submitData.start_time = targetDiv.find("input[name=input_startTime]").val();
                    submitData.end_time = targetDiv.find("input[name=input_endTime]").val();
                    submitData.album_name = targetDiv.find("span[name=span_album_name]").html();
                    submitData.qipu_id = targetDiv.find("span[name=span_qipu_id]").html();
                    submitData.channel = targetDiv.find("span[name=span_channel_name]").html();
                    if (!submitData.album_id || !submitData.album_name || !submitData.qipu_id || !submitData.channel || !submitData.news_name || !submitData.start_time || !submitData.end_time) {
                        submitData.msgData = {type: "error", msg: "参数不完整", index: 0}
                    } else if (submitData.start_time > submitData.end_time) {
                        submitData.msgData = {type: "error", msg: "时间范围格式错误", index: 0}
                    }
                    submitData.news_name = encodeURIComponent(submitData.news_name);
                    submitData.album_name = encodeURIComponent(submitData.album_name);
                    submitData.channel = encodeURIComponent(submitData.channel);
                    newArr.push(submitData);
                }
            })

            if (newArr.length > 0) {
                var map = {};
                $.each(newArr, function (i, element) {
                    if (!map.hasOwnProperty("" + element.qipu_id)) {
                        map["" + element.qipu_id] = [];
                    }
                    map["" + element.qipu_id].push(element);
                    if (map["" + element.qipu_id].length > 1) {
                        element.msgData = {type: "error", msg: "数据重复", index: map["" + element.qipu_id].length - 1}
                    }
                    if (element.msgData == null) {
                        validArr.push(element)
                    } else {
                        Specimen.Util.doErrorSpecimenCell(element.qipu_id, element.msgData.msg, element.msgData.index);
                    }
                })
            }
            if (validArr.length > 0) {
                if (Specimen.Config.queryComponent == null) {
                    Specimen.Config.queryComponent = Specimen.Util.getQueryComponent({
                        doBefore: function () {
                            Specimen.Util.disableEditSubmit();
                        },
                        doAfter: function () {
                            Specimen.Util.enableEditSubmit();
                        },
                        doSingle: function (element, notifyHandler) {
                            var queryElement = {albumId: element.album_id, globalPublishDateStart: element.start_time, globalPublishDateEnd: element.end_time};
                            Specimen.Dao.queryAlbumSource(queryElement, function (sourceData) {
                                if (sourceData == null) {
                                    Specimen.Util.doErrorSpecimenCell(element.qipu_id, "无法获取专辑成片，请联系lego人员!");
                                    notifyHandler()
                                } else if (sourceData.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                                    if (sourceData.data == null || sourceData.data.length == 0) {
                                        Specimen.Util.doErrorSpecimenCell(element.qipu_id, "没有专辑成片数据，请联系lego人员!");
                                        notifyHandler();
                                    } else {
                                        Specimen.Dao.addSpecimen(element, function (data) {
                                            console.log(element.qipu_id);
                                            if (data == null) {
                                                Specimen.Util.doErrorSpecimenCell(element.qipu_id, "请求异常");
                                            } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                                                Specimen.Util.doSucSpecimenCell(element.qipu_id, "提交成功")
                                            } else {
                                                Specimen.Util.doErrorSpecimenCell(element.qipu_id, data.msg);
                                            }
                                            notifyHandler()
                                        })
                                    }
                                } else {
                                    Specimen.Util.doErrorSpecimenCell(element.qipu_id, "获取专辑成片失败，请联系lego人员!错误：" + sourceData.msg);
                                    notifyHandler()
                                }
                            })
                        }
                    });
                }
                Specimen.Config.queryComponent.doInit(validArr);
            }
        },

        submitModifySpecimen: function () {
            var targetDiv = $("#modifyContainer");
            var submitData = {album_id: null, qipu_id: null, news_name: null}
            submitData.album_id = targetDiv.find("span[name=span_album_id]").html();
            submitData.qipu_id = targetDiv.find("span[name=span_qipu_id]").html();
            submitData.news_name = targetDiv.find("input[name=input_news_name]").val().trim();
            if (!submitData.news_name) {
                SystemDialog.queryAlert("新闻标题不能为空!")
                return;
            }
            submitData.news_name = encodeURIComponent(submitData.news_name)
            Specimen.Util.disableEditSubmit();
            Specimen.Dao.modifySpecimen(submitData, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({type: "error", content: " modifySpecimen 请求发生异常 "});
                } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                    EpgWeb.Plugin.showTips({ content: "修改成功"});
                } else {
                    EpgWeb.Plugin.showTips({type: "error", content: " modifySpecimen 请求失败: " + data.msg});
                }

                Specimen.Util.enableEditSubmit();
            })
        },
        disableEditSubmit: function () {
            $("button[name=btn_submit]").prop("disabled", "disabled");
        },
        enableEditSubmit: function () {
            $("button[name=btn_submit]").removeAttr("disabled");
        },
        showNoResult: function (dataLength, tableName) {
            if (tableName == null) {
                tableName = "#list"
            }
            var jqGridTarget = $(tableName);
            var parentElement = jqGridTarget.parent();
            if (parentElement.find(".norecords").html() == null) {
                parentElement.append('<div class="norecords">没有符合数据</div>');
                parentElement.find(".norecords").hide();
            }
            if (dataLength == 0) {
                parentElement.find(".norecords").show();
            } else {
                parentElement.find(".norecords").hide();
            }
        },
        getAlbumDataByUrl: function () {
            var element = {
                qipu_id: Com.url.getParameter("qipu_id"),
                album_id: Com.url.getParameter("album_id"),
                album_name: decodeURIComponent(Com.url.getParameter("album_name")),
                channel: decodeURIComponent(Com.url.getParameter("channel")),
                news_name: decodeURIComponent(Com.url.getParameter("news_name")).trim(),
                start_time: Com.url.getParameter("start_time"),
                end_time: Com.url.getParameter("end_time")
            };
            return element;
        },
        doQueryShot: function () {
            var parent = $("#sportContainer");
            var hostData = Specimen.Dao.getDataByTargetName("host_list");
            var params = { album_id: parent.find("span[name=album_id]").html(), qipu_id: parent.find("span[name=qipu_id]").html(), start: hostData.start, end: hostData.end };
            Specimen.Dao.getQueryShot(params, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({content: '主持人帧采样图片列表 请求异常 ', type: "error"})
                } else if (Specimen.Config.HINT_MSG.CODE_SUC == data.code) {
                    var hostData = Specimen.Dao.getDataByTargetName("host_list")
                    hostData.pic_total = data.data.total;
                    hostData.pic_update = data.data.update;
                    hostData.start += hostData.pic_update;
                    hostData.end += hostData.pic_update;
                    hostData.marked_total = data.data.label;
                    if(  data.data.result == null ){
                        data.data.result = [];
                    }
                    hostData.current_num =  data.data.result.length;
                    Specimen.Util.updateHostFrame();
                    $("#imageZone").html(Specimen.Util.fillImageZone(data.data.result));
                    $("#imageZone").scrollTop(0);
                } else {
                    EpgWeb.Plugin.showTips({content: '主持人帧采样图片列表 请求失败!' + data.msg, type: "error"})
                }
            });
        },
        submitSelectedHost: function () {
            var pidSpanArr = $("img.select-img").parent().find("span.pid");
            var selectedIdArr = [];
            $.each(pidSpanArr, function (i, element) {
                selectedIdArr.push(parseInt($(element).html()));
            })
            var element = null;
            var selectedIdArrLength = selectedIdArr.length;
            var source = Specimen.Config.PageBeanSpecimen.getSource();
            var unSelected = false;
            var submitArr = [];
            $.each(source, function (i, element) {
                unSelected = true;
                if (selectedIdArrLength > 0) {
                    unSelected = selectedIdArr.indexOf(element.pid) == -1;
                }
                if (!unSelected) {
                    selectedIdArrLength--;
                }
                submitArr.push(element.pic_addr + "_" + (unSelected ? 0 : 1))
            })
            console.log("submitArr  ", JSON.stringify(submitArr));
            var parent = $("#sportContainer");
            var params = {
                album_id: parent.find("span[name=album_id]").html(),
                qipu_id: parent.find("span[name=qipu_id]").html(),
                news_name: parent.find("span[name=news_name]").html(),
                pic_name: submitArr.join(",") };
            Specimen.Util.disableEditSubmit();
            Specimen.Dao.doUpdateShot(params, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({content: '更新主持人帧采样 请求异常 ', type: "error"})
                } else if (data.code == Specimen.Config.HINT_MSG.CODE_SUC) {
                    var hostData = Specimen.Dao.getDataByTargetName("host_list");
                    hostData.marked_current += selectedIdArr.length;
                    hostData.start += submitArr.length;
                    hostData.end += submitArr.length;
                    Specimen.Util.doQueryShot();
                } else {
                    EpgWeb.Plugin.showTips({content: '更新主持人帧采样 请求失败!' + data.msg, type: "error"})
                }
                Specimen.Util.enableEditSubmit();
            })
        },
        updateHostFrame: function () {
            var hostData = Specimen.Dao.getDataByTargetName("host_list");
            var parent = $("#sportContainer");
            parent.find("span[name=current_marked]").html(hostData.marked_current);
            parent.find("span[name=total_marked]").html(hostData.marked_total);
            parent.find("span[name=current_num]").html(hostData.current_num);
            parent.find("span[name=pic_rest]").html(hostData.pic_total - hostData.start);
        }
    });
});